package com.ruoyi.file.controller;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.framework.minio.MinioFile;
import com.ruoyi.framework.minio.MinioService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

@RestController
@RequestMapping("/minio")
public class MinioController {
    @Autowired
    private MinioService minioService;

    @PostMapping("/get/url")
    public AjaxResult getObjectUrl(@RequestBody MinioFile minioFile) throws Exception {
        String url = minioService.getBucketObjectUrl(minioFile.getBucket(),minioFile.getObjectName());
        return AjaxResult.success("请求成功",url);
    }

    @GetMapping("/url/{bucket}/{object}")
    public String getFileUrl(@PathVariable String bucket,@PathVariable String object) {
        String url = minioService.getBucketObjectUrl(bucket,object);
        return url;
    }



    @GetMapping("/object/{bucket}/{objectName}")
    public void getObject(@PathVariable("bucket")String bucket,
                          @PathVariable("objectName")String objectName, HttpServletResponse response) throws Exception {
        InputStream inputStream = minioService.getObject(bucket, objectName);
        IOUtils.copy(inputStream,response.getOutputStream());
    }


    @PostMapping("/upload/{bucket}")
    public AjaxResult uploadFile(@PathVariable("bucket")String bucket,
                                 MultipartFile file) throws Exception
    {
        try
        {
            if(bucket==null)return AjaxResult.error("上传位置不能为空");
            MinioFile upload = minioService.upload(bucket, file);
            if(upload==null)return AjaxResult.error("上传文件失败");
            AjaxResult ajax = AjaxResult.success(upload);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }
}
